﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SportManager
{
    public partial class EditTrainingDlg : Form
    {
        public Training training;
        
        public EditTrainingDlg(Training Training)
        {
            InitializeComponent();

            dialogHeader1.SetHeaderText("Редактирование тренировки");
            dialogHeader1.SetDescriptionText("Здесь вы можете отредактировать список упражнений и подходов.");
            this.Text = Training.StartDate.ToShortTimeString();
            training = Training;
            label3.Text = "";
            ShowExercises();

            if (training.IsReadOnly)
            {
                button1.Enabled = false;
                button2.Enabled = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<ExerciseInfo> infos = new List<ExerciseInfo>();
            foreach (Exercise item in training.Exercises)
            {
                infos.Add(Program.ExercisesKeeper.FindItemByGuid(item.Id));
            }

            ExercisesListDlg dlg = new ExercisesListDlg(true, infos);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                training.Exercises = ExerciseMerger.MergeLists(dlg.SelectedInfos, training.Exercises);
            }

            ShowExercises();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Вы уверены ?", "Удаление", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    training.Exercises.RemoveAt(listBox1.SelectedIndex);
                    listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                    ClearExercise();
                }
            }
            else
            {
                MessageBox.Show("Не выбрано ни одно из упражнений", "Ошибка", MessageBoxButtons.OK);
            }
        }

        private void ShowExercises()
        {
            listBox1.Items.Clear();
            for (int i = 0; i < training.Exercises.Count; i++)
            {
                listBox1.Items.Add(Program.ExercisesKeeper.FindItemByGuid(training.Exercises[i].Id).Name);
            }
        }

        private void ClearExercise()
        {
            label1.Text = "";
            label2.Text = "";
            label3.Text = "";

            button5.Enabled = false;
            tableLayoutPanel1.Controls.Clear();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
            if ((listBox1.SelectedIndex >= 0)&&(training.Exercises[listBox1.SelectedIndex].Approachs.Count > 0))
            {
                SaveApproachs();
            }
             */
            ClearExercise();
            if (listBox1.SelectedIndex >= 0)
            {
                ShowApproachs();
            }
        }

        private void ShowApproachs()
        {
            ClearExercise();
            button5.Enabled = (training.IsReadOnly == true) ? false : true;
            label1.Text = "повторы";
            label2.Text = "вес";
            ExerciseInfo info = Program.ExercisesKeeper.FindItemByGuid(training.Exercises[listBox1.SelectedIndex].Id);
            label3.Text = info.Name;

            if (training.Exercises[listBox1.SelectedIndex].PlanningApproachs != null)
            {
                for (int i = 0; i < training.Exercises[listBox1.SelectedIndex].PlanningApproachs.Count; i++)
                {
                    tableLayoutPanel1.Controls.Add(new TextBox(), 0, (i * 2));
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].PlanningApproachs[i].Repeats.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;

                    tableLayoutPanel1.Controls.Add(new TextBox(), 1, (i * 2));
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].PlanningApproachs[i].Weight.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;

                    tableLayoutPanel1.Controls.Add(new TextBox(), 2, (i * 2));
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].PlanningApproachs[i].Time.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
                }
            }
             
            for (int i = 0; i < training.Exercises[listBox1.SelectedIndex].Approachs.Count; i++)
            {
                tableLayoutPanel1.Controls.Add(new TextBox(), 0, (i * 2 + 1));
                if (info.IsRepeatsRequired)
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].Approachs[i].Repeats.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].LostFocus += new EventHandler(EditTrainingDlg_LostFocus);
                }
                else
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
                }

                tableLayoutPanel1.Controls.Add(new TextBox(), 1, (i * 2 + 1));
                if (info.IsWeightRequired)
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].Approachs[i].Weight.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].LostFocus += new EventHandler(EditTrainingDlg_LostFocus);
                }
                else
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
                }

                tableLayoutPanel1.Controls.Add(new TextBox(), 2, (i * 2 + 1));
                if (info.IsTimeSpanRequired)
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = training.Exercises[listBox1.SelectedIndex].Approachs[i].Time.ToString();
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].LostFocus += new EventHandler(EditTrainingDlg_LostFocus);
                }
                else
                {
                    tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
                }

                CheckBox checkBox = new CheckBox();
                checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
                tableLayoutPanel1.Controls.Add(checkBox, 3, (i * 2 + 1));
            }
        }

        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = (CheckBox)sender;
            if (checkBox.Checked)
            {
                button6.Enabled = (training.IsReadOnly == true) ? false : true;
            }
        }

        private void EditTrainingDlg_LostFocus(object sender, EventArgs e)
        {
            SaveApproachs();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            training.Exercises[listBox1.SelectedIndex].Approachs.Add(new Approach());
            
            ExerciseInfo info = Program.ExercisesKeeper.FindItemByGuid(training.Exercises[listBox1.SelectedIndex].Id);
            
            int count = training.Exercises[listBox1.SelectedIndex].Approachs.Count - 1;
            tableLayoutPanel1.Controls.Add(new TextBox(), 0, (count * 2 + 1));
            tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = "0";
            if (!info.IsRepeatsRequired)
            {
                tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
            }
            tableLayoutPanel1.Controls.Add(new TextBox(), 1, (count * 2 + 1));
            tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = "0";
            if (!info.IsWeightRequired)
            {
                tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
            }

            tableLayoutPanel1.Controls.Add(new TextBox(), 2, (count * 2 + 1));
            tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Text = "0";
            if (!info.IsTimeSpanRequired)
            {
                tableLayoutPanel1.Controls[tableLayoutPanel1.Controls.Count - 1].Enabled = false;
            }

            CheckBox checkBox = new CheckBox();
            checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
            tableLayoutPanel1.Controls.Add(checkBox, 3, (count * 2 + 1));
             
        }
        
        private void button6_Click(object sender, EventArgs e)
        {
            SaveApproachs();
            ArrayList array = new ArrayList();
            if (MessageBox.Show("Вы уверены ?", "Удаление", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                for (int i = 0; i < training.Exercises[listBox1.SelectedIndex].Approachs.Count; i++)
                {
                    CheckBox checkBox = (CheckBox)tableLayoutPanel1.GetControlFromPosition(3, (i * 2 + 1));
                    if (checkBox.Checked)
                    {
                        array.Add((i));
                    }
                }

                for (int i = array.Count-1; i >=0 ; i--)
                {
                    training.Exercises[listBox1.SelectedIndex].Approachs.RemoveAt((int)array[i]);
                    for (int j = 0; j < 3; j++)
                    {
                        tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j, (int)array[i]));
                    }
                }

                if (array.Count == 0)
                {
                    MessageBox.Show("Не выбран ни один подход", "Ошибка", MessageBoxButtons.OK);
                    button6.Enabled = false;
                }

                ShowApproachs();
            }
        }

        private void SaveApproachs()
        {
            System.Globalization.NumberFormatInfo numFormat = new System.Globalization.NumberFormatInfo();
            numFormat.NumberDecimalSeparator = ",";

            ExerciseInfo info = Program.ExercisesKeeper.FindItemByGuid(training.Exercises[listBox1.SelectedIndex].Id);
            for (int i = 0; i < training.Exercises[listBox1.SelectedIndex].Approachs.Count; i++)
            {
                if (info.IsRepeatsRequired)
                {
                    int repeats = 0;
                    if (int.TryParse((tableLayoutPanel1.GetControlFromPosition(0, (i * 2 + 1)).Text), out repeats))
                    {
                        training.Exercises[listBox1.SelectedIndex].Approachs[i].Repeats = repeats;
                    }
                    else
                    {
                        tableLayoutPanel1.GetControlFromPosition(0, i).Text = "0";
                        MessageBox.Show("Неверное значение", "", MessageBoxButtons.OK);
                    }
                }

                if (info.IsWeightRequired)
                {
                    double weight = 0;
                    if (double.TryParse((tableLayoutPanel1.GetControlFromPosition(1, (i * 2 + 1)).Text)
                        , System.Globalization.NumberStyles.Number, numFormat, out weight)                        )
                    {
                        training.Exercises[listBox1.SelectedIndex].Approachs[i].Weight = weight;
                    }
                    else
                    {
                        tableLayoutPanel1.GetControlFromPosition(1, i).Text = "0";
                        MessageBox.Show("Неверное значение", "", MessageBoxButtons.OK);
                    }
                }

                if (info.IsTimeSpanRequired)
                {
                    int time = 0;
                    if (int.TryParse((tableLayoutPanel1.GetControlFromPosition(2, (i * 2 + 1)).Text), out time))
                    {
                        training.Exercises[listBox1.SelectedIndex].Approachs[i].Time = time;
                    }
                    else
                    {
                        tableLayoutPanel1.GetControlFromPosition(2, i).Text = "0";
                        MessageBox.Show("Неверное значение", "", MessageBoxButtons.OK);
                    }
                }
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            SaveApproachs();
        }
    }
}
